package com.kmu.kmucampus.Fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.kmu.kmucampus.R;
import com.kmu.kmucampus.activity.MainActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import mytest.ssw.www.api.ActionCallbackListener;
import mytest.ssw.www.api.ApiResponse;
import mytest.ssw.www.core.sqLiteTools;
import mytest.ssw.www.mylibrary.Contents;

//import android.app.Fragment;

/**
 * Created by Administrator on 2016/4/14 0014.
 */
public class AddrDetailFragment extends ListFragment {
    public BackHandlerInterface backHandlerInterface;
    int lay;
    ProgressDialog progressDialog;
    private View vw;
    private boolean mHandledPress = false;
    List<Contents> content;
    sqLiteTools sqlTool;
    static String TB_STU="TB_STU";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_addr_detail, container, false);
        Log.d("addrDT", "CREATEVIEW");
        lay= android.R.layout.simple_expandable_list_item_1;
        vw=view;
        initLvContactInfo();
        Log.d("addrDT", "setText");
        return view;
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        if(savedInstanceState!=null){
            Log.d("Deatail-create","save is not null");
        }
        super.onCreate(savedInstanceState);
        //回调函数赋值
        if(!(getActivity() instanceof BackHandlerInterface)) {
            throw new ClassCastException("Hosting activity must implement BackHandlerInterface");
        } else {
            backHandlerInterface = (BackHandlerInterface) getActivity();
        }
        sqlTool=new sqLiteTools(getActivity().getFilesDir().toString());

    }
    public  void initLvContactInfo(){
        String deptNo= getArguments().getString("deptNo");
        Log.d("Detail:", deptNo);
        HashMap<String,String> mapToContactInfo= new HashMap<>();
        mapToContactInfo.put("departmentNum", deptNo);

        progressDialog=new ProgressDialog(getActivity());
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        Window window = progressDialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.alpha = 100f;// 透明度
        lp.dimAmount = 0.8f;// 黑暗度
        window.setAttributes(lp);
        progressDialog.setCancelable(true);
        progressDialog.setIndeterminate(true);
        progressDialog.setTitle("加载信息");
        progressDialog.setMessage("正在加载....");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(true);
        progressDialog.setButton("取消", new BtDialogListener());
        progressDialog.show();
        content = sqlTool.getTeacherInfoFrDB(TB_STU, deptNo);
        Log.d("initLvContactInfo","-----"+TB_STU+"----"+deptNo);
        String CONNECT_TYPE=((MainActivity) getActivity()).appAction.getNetworkInfo(getContext());
        Log.d("CONNECT_TYPE", "" + CONNECT_TYPE);
        if( content.size()==0 || CONNECT_TYPE=="WIFI") {
            Log.d("initLvContactInfo","from Intnet------"+Integer.toString(content.size())+"---+"+deptNo);
            ((MainActivity) getActivity()).appAction.SearchInfo(mapToContactInfo, new ActionCallbackListener<ApiResponse<List<Contents>>>() {
                @Override
                public void onSuccess(ApiResponse<List<Contents>> data) {
                    progressDialog.dismiss();
                    initItem(data.getContents());
                    Log.d("getRecordCount_detail", "" + getActivity().getFilesDir().toString());
                    Log.d("getRecordCount_data", "" + data.getContents().size());
                    sqlTool.insertTeacherInfo("TB_STU", data.getContents());
                    Log.d("getRecordCount_detail", "" + sqlTool.getRecordCount(TB_STU));
                }
                @Override
                public void onFailure(String errorEvent, String message) {
                    progressDialog.dismiss();
                    Toast.makeText(getActivity(), "获取不到数据。", Toast.LENGTH_SHORT).show();
                    onBackPressed();
                }
            });
        }
        else{
            Log.d("initLvContactInfo","from DB-------"+Integer.toString(content.size()));
            AsyncTask<Void, Void, Boolean> res = new AsyncTask<Void, Void, Boolean>()
            {            @Override
                         protected Boolean doInBackground(Void... voids) {
                    return  initItem(content);
                }
                @Override
                protected void onPostExecute(Boolean flag) {
                }
            }.execute();
            progressDialog.dismiss();
        }

        progressDialog.dismiss();
    }

    public boolean initItem(final List<Contents> data){
        boolean flag=false;

        Log.d("showInfo", "succ");
        final String[] itemList = new String[data.size()];
        List<Map<String, Object>> listems = new ArrayList<>();
        Log.d("initList:", Integer.toString(data.size()));
        for (int i = 0; i < data.size(); i++) {
            itemList[i] = data.get(i).getName();
            Map<String, Object> listem = new HashMap<>();
            listem.put("stuName",data.get(i).getName());
            listems.add(listem);
        }
        SimpleAdapter adapter = new SimpleAdapter(getContext(), listems, R.layout.addr_detail_item, new String[]{"stuName"}, new int[]{R.id.addrClassItem});
        ListView lv_contactInfo = (ListView) vw.findViewById(android.R.id.list);
        lv_contactInfo.setAdapter(adapter);
        TextView itemTV=(TextView) vw.findViewById(R.id.addrClassItem);
        lv_contactInfo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d("initList____onItemClick", Integer.toString(data.size()));
                showInfo(position, data);
            }
        });
        flag=true;
        return flag;
    }


    public void showInfo(final int index, final List<Contents> data){
        AlertDialog.Builder alertDialog= new AlertDialog.Builder(getActivity());
        alertDialog.setTitle(data.get(index).getName());
        alertDialog.setMessage("班级:" + data.get(index).getClassName() + "\n"
                + "宿舍:" + data.get(index).getDormitory()+ "\n"
                + "手机:" + data.get(index).getPhoneNum());
        alertDialog.setPositiveButton("返回", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        if(data.get(index).getPhoneNum()!=null) {
            alertDialog.setNegativeButton("拨号", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + data.get(index).getPhoneNum()));
                            startActivity(intent);
                        }
                    }
            );
        }
        alertDialog.show();
    }

    @Override
    public void onStart() {
        super.onStart();
        //将自己的实例传出去
        backHandlerInterface.setSelectedFragment(this);
    }


    public boolean onBackPressed(){
        if (!mHandledPress){
            //   AddrBookFragment addrBookFragment=new AddrBookFragment();
            Log.d("Bck","bk");
            getActivity().getSupportFragmentManager().beginTransaction().hide(this).commit();

            //getActivity().getSupportFragmentManager().beginTransaction().add(R.id.vPager,addrBookFragment).remove(this).show(addrBookFragment);
            mHandledPress = true;
            return true;
        }
        return false;
    }
    public interface BackHandlerInterface {
        public abstract void setSelectedFragment(AddrDetailFragment backHandledFragment);
    }
    class BtDialogListener implements DialogInterface.OnClickListener {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // 点击“确定”按钮取消对话框
            dialog.cancel();
        }
    }

}
